package com.magupe.push.server.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.magupe.push.common.attribute.Attributes;
import com.magupe.push.common.session.AuthenticationSession;

import io.netty.channel.Channel;

public class AuthenticationSessionUtil {

	private static final Map<String, Channel> channelMap = new ConcurrentHashMap<>();
	
	public static void bindAuthenticationSession(AuthenticationSession authenticationSession, Channel channel) {
		channelMap.put(authenticationSession.getSecret(), channel);
		channel.attr(Attributes.AUTHENTICATIONSESSION).set(authenticationSession);
	}

    public static void unBindAuthenticationSession(Channel channel) {
        if (hasAuthentication(channel)) {
        	channelMap.remove(getAuthenticationSession(channel).getSecret());
        	channel.attr(Attributes.AUTHENTICATIONSESSION).set(null);
        }
    }
    
    public static boolean hasAuthentication(Channel channel) {
        return channel.hasAttr(Attributes.AUTHENTICATIONSESSION);
    }
    
    public static AuthenticationSession getAuthenticationSession(Channel channel) {
        return channel.attr(Attributes.AUTHENTICATIONSESSION).get();
    }

    public static Channel getChannel(String secret) {
        return channelMap.get(secret);
    }
}
